import {
    ConnectedSocket,
    MessageBody,
    OnGatewayConnection,
    OnGatewayDisconnect,
    SubscribeMessage,
    WebSocketGateway,
    WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { ENUM_WS_EVENT } from '../room.enum.constant';
import { RoomInitGuard } from '../../decorators/ws.decorator';
import { RoomInitDto } from '../../dtos/room.ws.dto';

@WebSocketGateway(80, {
    cors: {
        origin: '*',
    },
    path: '/io',
    transports: ['polling', 'websocket'],
})
export class InitWSGateway implements OnGatewayConnection, OnGatewayDisconnect {
    @WebSocketServer()
    server: Server;

    handleConnection(client: Socket, ...args: any[]) {
        // client.data['x-api-key'] = client.handshake.headers['x-api-key'];
        // client.data['x-device-uuid'] = client.handshake.headers['x-device-uuid'];
        // console.log(client.handshake.headers['x-device-uuid']);
        try {
            client.emit(ENUM_WS_EVENT.ROOM, { connection: 'OK' });
        } catch (error) {
            console.error('Error sending response:', error);
        }
    }

    handleDisconnect(client: Socket, ...args: any[]): any {
        console.log('Client disconnected:', client.data);
    }

    @SubscribeMessage(ENUM_WS_EVENT.ROOM)
    initRoom(
        @MessageBody() data: RoomInitDto,
        @ConnectedSocket() client: Socket
    ) {
        client.data.roomId = data.roomId; // кладем в контекст
        client.join(data.roomId); // Устанавливаем комнату
        try {
            client.emit(ENUM_WS_EVENT.ROOM, {
                roomId: client.data.roomId,
                connection: '200',
            });
        } catch (error) {
            console.error('Error sending response:', error);
        }
    }

    afterInit() {}

    @RoomInitGuard()
    @SubscribeMessage(ENUM_WS_EVENT.EVENT)
    handleYourEvent(client: Socket, payload: any): void {
        this.server.to(client.data.roomId).emit(ENUM_WS_EVENT.EVENT, {
            roomId: client.data.roomId, // берем из контекста
            apiKey: client.handshake.headers['x-api-key'], // берем из контекста рукопожатия лонгпулингом
            deviceID: client.handshake.headers['x-device-uuid'],
        });
        // отправляем всем кто подключен к комнате
    }
}
